<template>
    <div>
        <van-grid clickable :column-num="4">
            <van-grid-item icon="bookmark-o" text="初始化数据库信息" @click="daInfo" />
        </van-grid>
        <van-list v-model="loading" :finished="finished" finished-text="没有更多了">
            <van-cell v-for="item in demoList" :key="item">
                <template>
                    <div style="display: flex;">
                        <span>{{ item }}</span>
                    </div>
                </template>
            </van-cell>
        </van-list>
    </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from 'vue'

export default {
    name: "InitDataBase",
    setup() {
        const dbContext = ref(null);
        const loading = ref(false);
        const finished = ref(false);
        const demoList = ref([])

        const daInfo = () => {
            try {
                demoList.value = [];
                loading.value = true;
                dbContext.value = window.sqlitePlugin.openDatabase({
                    name: "ramac.db",
                    location: 'default',
                    androidDatabaseProvider: 'system'
                });
                demoList.value.push(JSON.stringify(dbContext.value.openargs));

                dbContext.value.transaction(function (tx) {
                    tx.executeSql(`CREATE TABLE IF NOT EXISTS DemoTable (name, score)`);
                    tx.executeSql('INSERT INTO DemoTable VALUES (?,?)', ['Alice', 101]);
                }, function (error) {
                    loading.value = false;
                    finished.value = true;
                    demoList.value.push('初始化错误：' + JSON.stringify(error.message));
                }, function () {
                    loading.value = false;
                    finished.value = true;
                    demoList.value.push('初始化：数据表数据化完成');
                })

            } catch (error) {
                demoList.value.push(error);
                loading.value = false;
                finished.value = true;
            }

        }
        onMounted(function () {

        })
        onUnmounted(function () {
            dbContext.value = null
        })
        return {
            demoList,
            daInfo
        }
    }
}

</script>

<style></style>
